package com.budwk.app.sqfw.services.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.dto.SqfwSummaryPdfExcelCollForAdminDTO;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SqfwCheckRecordForAdminService;
import com.budwk.app.sqfw.services.SqfwSummaryForAdminService;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.AuthorityUtil;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.database.service.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: wk-mini
 * @description: 巡查记录服务实现
 * @author: LJT
 * @create: 2023-11-07 08:41
 **/
@IocBean(args = {"refer:dao"})
public class SqfwCheckRecordForAdminServiceImpl extends BaseServiceImpl<Sqfw_formSummary> implements SqfwCheckRecordForAdminService {
    public SqfwCheckRecordForAdminServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;
    @Inject
    private SysUserService sysUserService;
    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;

    /**
     * 获取pdfExcel下载sumId列表
     *
     * @param bean
     * @param pageOrderName
     * @param pageOrderBy
     * @return
     */
    @Override
    public List<SqfwSummaryPdfExcelCollForAdminDTO> getPdfExcelFileDownSumIdList(Sqfw_formSummaryForAdminVO bean, String pageOrderName, String pageOrderBy) {
        String sql = buildConditionForQueryToString(bean);
        return sqfwSummaryForAdminService.getPdfExcelFileDownSumIdList(sql, bean.getType());
    }


    /**
     * 获取巡查记录的查询条件 Cnd类型
     *
     * @param bean
     * @param pageOrderName
     * @param pageOrderBy
     */
    public Result<?> listForHouseSurvey(Sqfw_formSummaryForAdminVO bean, String pageOrderName, String pageOrderBy) {
       /* AuthorityUtil.checkFormSummaryAreaPermission(bean);
        bean.setType(SqfwFormSummaryConstants.house_survey_form);
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("fill_date", "desc");
        }
        if (Strings.isNotBlank(bean.getQueryAll())) {
            String queryAll = bean.getQueryAll();
            SqlExpressionGroup e1 = Cnd.exps("a1", "like", "%" + queryAll + "%");
            SqlExpressionGroup e2 = Cnd.exps("a2", "like", "%" + queryAll + "%");
            SqlExpressionGroup e3 = Cnd.exps("a3", "like", "%" + queryAll + "%");
            SqlExpressionGroup e4 = Cnd.exps("a4", "like", "%" + queryAll + "%");
            SqlExpressionGroup e5 = Cnd.exps("a5", "like", "%" + queryAll + "%");
            SqlExpressionGroup e6 = Cnd.exps("a16", "like", "%" + queryAll + "%");
            SqlExpressionGroup e7 = Cnd.exps("a17", "like", "%" + queryAll + "%");
            SqlExpressionGroup e8 = Cnd.exps("a18", "like", "%" + queryAll + "%");
            SqlExpressionGroup e9 = Cnd.exps("a20", "like", "%" + queryAll + "%");
            SqlExpressionGroup e10 = Cnd.exps("create_user_name", "like", "%" + queryAll + "%");
            cnd.and(e1.or(e2).or(e3).or(e4).or(e5).or(e6).or(e7).or(e8).or(e9));
        }
        // 网格
        if (Strings.isNotBlank(bean.getA3())) {
            cnd.and("a3", "like", "%" + bean.getA3() + "%");
        }
        // 院落名称
        if (Strings.isNotBlank(bean.getA1())) {
            cnd.and("a1", "like", "%" + bean.getA1() + "%");
        }
        // 楼栋
        if (Strings.isNotBlank(bean.getA4())) {
            cnd.and("a4", "like", "%" + bean.getA4() + "%");
        }
        // 单元户号
        if (Strings.isNotBlank(bean.getA5())) {
            cnd.and("a5", "like", "%" + bean.getA5() + "%");
        }
        // 房屋类型
        if (Strings.isNotBlank(bean.getA18())) {
            cnd.and("a18", "like", "%" + bean.getA18() + "%");
        }
        // 房屋状态
        if (Strings.isNotBlank(bean.getA17())) {
            cnd.and("a17", "like", "%" + bean.getA17() + "%");
        }
        // 调查类型
        if (Strings.isNotBlank(bean.getA16())) {
            cnd.and("a16", "like", "%" + bean.getA16() + "%");
        }
        // 调查人员
        if (Strings.isNotBlank(bean.getCreateUserName())) {
            cnd.and("create_user_name", "like", "%" + bean.getCreateUserName() + "%");
        }
        // 入户情况
        if (Strings.isNotBlank(bean.getA20())) {
            if ("入户成功".equals(bean.getA20())) {
                SqlExpressionGroup e1 = Cnd.exps("a20", "=", "入户成功");
                SqlExpressionGroup e2 = Cnd.exps("a20", "=", "无");
                cnd.and(e1.or(e2));
            } else if ("空置".equals(bean.getA20())) {
                SqlExpressionGroup e1 = Cnd.exps("a20", "=", "空置");
                SqlExpressionGroup e2 = Cnd.exps("a20", "=", "空房");
                cnd.and(e1.or(e2));
            } else {
                cnd.and("a20", "=", bean.getA20());
            }
        }
        // 住户姓名
        if (Strings.isNotBlank(bean.getA2())) {
            cnd.and("a2", "like", "%" + bean.getA2() + "%");
        }
        // 住户手机
        if (Strings.isNotBlank(bean.getA8())) {
            cnd.and("a8", "like", "%" + bean.getA8() + "%");
        }
        // 省
        if (Strings.isNotBlank(bean.getProvince())) {
            cnd.and("province", "like", "%" + bean.getProvince() + "%");
        }
        // 市
        if (Strings.isNotBlank(bean.getCity())) {
            cnd.and("city", "like", "%" + bean.getCity() + "%");
        }
        // 区
        if (Strings.isNotBlank(bean.getDistrict())) {
            cnd.and("district", "like", "%" + bean.getDistrict() + "%");
        }
        // 街道
        if (Strings.isNotBlank(bean.getCounty())) {
            cnd.and("county", "like", "%" + bean.getCounty() + "%");
        }
        // 社区
        if (Strings.isNotBlank(bean.getCommunity())) {
            cnd.and("community", "like", "%" + bean.getCommunity() + "%");
        }
        // 业务类型
        if (Strings.isNotBlank(bean.getType())) {
            cnd.and("type", "like", "%" + bean.getType() + "%");
        }
        //数据库中存在这种"0001-01-01 00:00:00.000" 历史数据， 需要过滤掉
        cnd.and("fill_date", "!=", DateUtil.parse("0001-01-01 00:00:00.000"));
        // 时间区间
        if (bean.getQueryTime() != null && Strings.isNotBlank(bean.getQueryTime())) {
            String time[] = bean.getQueryTime().split(",");
            cnd.and("fill_date", "between", new Object[]{new Date(Long.valueOf(time[0])), new Date(Long.valueOf(time[1]))});
        }*/
        //zhangp 2023-12-07 提出条件公用
        Cnd cnd = buildCndParam(bean, pageOrderName, pageOrderBy);
        Pagination pagination = sqfwSummaryForAdminService.listPage(bean.getPageNo(), bean.getPageSize(), cnd);
        // 解析返回参数
        if (pagination.getTotalCount() > 0) {
            CompletableFuture[] cf = pagination.getList(Sqfw_formSummary.class).stream().map(data -> CompletableFuture.runAsync(() ->
                            countResidentNumber(data), taskQueryExecutor)
                    .thenApply(r -> r)).toArray(CompletableFuture[]::new);
            CompletableFuture.allOf(cf).join();
        }
        return Result.success(pagination);
    }

    @Override
    public Cnd buildCndParam(Sqfw_formSummaryForAdminVO bean, String pageOrderName, String pageOrderBy) {
        AuthorityUtil.checkFormSummaryAreaPermission(bean);
        bean.setType(SqfwFormSummaryConstants.house_survey_form);
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("fill_date", "desc");
        }
        if (Strings.isNotBlank(bean.getQueryAll())) {
            String queryAll = bean.getQueryAll();
            SqlExpressionGroup e1 = Cnd.exps("a1", "like", "%" + queryAll + "%");
            SqlExpressionGroup e2 = Cnd.exps("a2", "like", "%" + queryAll + "%");
            SqlExpressionGroup e3 = Cnd.exps("a3", "like", "%" + queryAll + "%");
            SqlExpressionGroup e4 = Cnd.exps("a4", "like", "%" + queryAll + "%");
            SqlExpressionGroup e5 = Cnd.exps("a5", "like", "%" + queryAll + "%");
            SqlExpressionGroup e6 = Cnd.exps("a16", "like", "%" + queryAll + "%");
            SqlExpressionGroup e7 = Cnd.exps("a17", "like", "%" + queryAll + "%");
            SqlExpressionGroup e8 = Cnd.exps("a18", "like", "%" + queryAll + "%");
            SqlExpressionGroup e9 = Cnd.exps("a20", "like", "%" + queryAll + "%");
            SqlExpressionGroup e10 = Cnd.exps("create_user_name", "like", "%" + queryAll + "%");
            SqlExpressionGroup e11 = Cnd.exps("county", "like", "%" + queryAll + "%");
            SqlExpressionGroup e12 = Cnd.exps("community", "like", "%" + queryAll + "%");
            SqlExpressionGroup e13 = Cnd.exps("a8", "like", "%" + queryAll + "%");
            cnd.and(e1.or(e2).or(e3).or(e4).or(e5).or(e6).or(e7).or(e8).or(e9).or(e10).or(e11).or(e12).or(e13));
        }
        // 网格
        if (Strings.isNotBlank(bean.getA3())) {
            cnd.and("a3", "like", "%" + bean.getA3() + "%");
        }
        // 院落名称
        if (Strings.isNotBlank(bean.getA1())) {
            cnd.and("a1", "like", "%" + bean.getA1() + "%");
        }
        // 楼栋
        if (Strings.isNotBlank(bean.getA4())) {
            cnd.and("a4", "like", "%" + bean.getA4() + "%");
        }
        // 单元户号
        if (Strings.isNotBlank(bean.getA5())) {
            cnd.and("a5", "like", "%" + bean.getA5() + "%");
        }
        // 房屋类型
        if (Strings.isNotBlank(bean.getA18())) {
            cnd.and("a18", "like", "%" + bean.getA18() + "%");
        }
        // 房屋状态
        if (Strings.isNotBlank(bean.getA17())) {
            cnd.and("a17", "like", "%" + bean.getA17() + "%");
        }
        // 调查类型
        if (Strings.isNotBlank(bean.getA16())) {
            cnd.and("a16", "like", "%" + bean.getA16() + "%");
        }
        // 调查人员
        if (Strings.isNotBlank(bean.getCreateUserName())) {
            cnd.and("create_user_name", "like", "%" + bean.getCreateUserName() + "%");
        }
        // 入户情况
        if (Strings.isNotBlank(bean.getA20())) {
            if ("入户成功".equals(bean.getA20())) {
                SqlExpressionGroup e1 = Cnd.exps("a20", "=", "入户成功");
                SqlExpressionGroup e2 = Cnd.exps("a20", "=", "无");
                cnd.and(e1.or(e2));
            } else if ("空置".equals(bean.getA20())) {
                SqlExpressionGroup e1 = Cnd.exps("a20", "=", "空置");
                SqlExpressionGroup e2 = Cnd.exps("a20", "=", "空房");
                cnd.and(e1.or(e2));
            } else {
                cnd.and("a20", "=", bean.getA20());
            }
        }
        // 住户姓名
        if (Strings.isNotBlank(bean.getA2())) {
            cnd.and("a2", "like", "%" + bean.getA2() + "%");
        }
        // 住户手机
        if (Strings.isNotBlank(bean.getA8())) {
            cnd.and("a8", "like", "%" + bean.getA8() + "%");
        }
        // 省
        if (Strings.isNotBlank(bean.getProvince())) {
            cnd.and("province", "like", "%" + bean.getProvince() + "%");
        }
        // 市
        if (Strings.isNotBlank(bean.getCity())) {
            cnd.and("city", "like", "%" + bean.getCity() + "%");
        }
        // 区
        if (Strings.isNotBlank(bean.getDistrict())) {
            cnd.and("district", "like", "%" + bean.getDistrict() + "%");
        }
        // 街道
        if (Strings.isNotBlank(bean.getCounty())) {
            cnd.and("county", "like", "%" + bean.getCounty() + "%");
        }
        // 社区
        if (Strings.isNotBlank(bean.getCommunity())) {
            cnd.and("community", "like", "%" + bean.getCommunity() + "%");
        }
        // 业务类型
        if (Strings.isNotBlank(bean.getType())) {
            cnd.and("type", "like", "%" + bean.getType() + "%");
        }
        //数据库中存在这种"0001-01-01 00:00:00.000" 历史数据， 需要过滤掉
        cnd.and("fill_date", "!=", DateUtil.parse("0001-01-01 00:00:00.000"));
        // 时间区间
        if (bean.getQueryTime() != null && Strings.isNotBlank(bean.getQueryTime())) {
            String time[] = bean.getQueryTime().split(",");
            cnd.and("fill_date", "between", new Object[]{new Date(Long.valueOf(time[0])), new Date(Long.valueOf(time[1]))});
        }
        return cnd;
    }

    // 计算居住人
    private void countResidentNumber(Sqfw_formSummary formSummary) {
        String a7 = formSummary.getA7();
        if (StringUtils.isEmpty(a7)) {
            return;
        }
        List<Sqfw_cenSusPaper> specialMarkVos = JSONObject.parseArray(formSummary.getA7(), Sqfw_cenSusPaper.class);
        long count = specialMarkVos.stream().filter(e -> StringUtils.isEmpty(e.getLatestStatus())).map(Sqfw_cenSusPaper::getName).distinct().count();
        formSummary.setResidentNumber(Math.toIntExact(count));
    }


    /**
     * 获取巡查记录的查询条件 String类型
     *
     * @param bean
     * @return
     */
    private String buildConditionForQueryToString(Sqfw_formSummaryForAdminVO bean) {
        bean.setType("入户调查");
        StringBuffer sb = new StringBuffer(" select * from shequ.\"sqfw_form_summary\" where 1 = 1 ");
        if (Strings.isNotBlank(bean.getQueryAll())) {
            String queryAll = bean.getQueryAll();
            sb.append(" and ( a1 like '%").append(queryAll).append("%'")
                    .append(" OR a2 like '%").append(queryAll).append("%'")
                    .append(" OR a3 like '%").append(queryAll).append("%'")
                    .append(" OR a4 like '%").append(queryAll).append("%'")
                    .append(" OR a5 like '%").append(queryAll).append("%'")
                    .append(" OR a8 like '%").append(queryAll).append("%'")
                    .append(" OR a16 like '%").append(queryAll).append("%'")
                    .append(" OR a17 like '%").append(queryAll).append("%'")
                    .append(" OR a18 like '%").append(queryAll).append("%'")
                    .append(" OR a20 like '%").append(queryAll).append("%'")
                    .append(" OR community like '%").append(queryAll).append("%'")
                    .append(" OR create_user_name like '%").append(queryAll).append("%'")
                    .append(" OR type like '%").append(queryAll).append("%')");
        }
        if (Strings.isNotBlank(bean.getA1())) {
            sb.append(" and a1 like '%").append(bean.getA1()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA2())) {
            sb.append(" and a2 like '%").append(bean.getA2()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA3())) {
            sb.append(" and a3 like '%").append(bean.getA3()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA5())) {
            sb.append(" and a5 like '%").append(bean.getA5()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA8())) {
            sb.append(" and a8 like '%").append(bean.getA8()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA16())) {
            sb.append(" and a16 like '%").append(bean.getA16()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA17())) {
            sb.append(" and a17 like '%").append(bean.getA17()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA18())) {
            sb.append(" and a18 like '%").append(bean.getA18()).append("%'");
        }
        if (Strings.isNotBlank(bean.getA20())) {
            if ("入户成功".equals(bean.getA20())) {
                sb.append(" and (a20 = '入户成功' OR a20 = '无')");
            } else if ("空置".equals(bean.getA20())) {
                sb.append(" and (a20 = '空置' OR a20 = '空房')");
            } else {
                sb.append(" and a20 = '").append(bean.getA20()).append("'");
            }
        }
        if (Strings.isNotBlank(bean.getProvince())) {
            sb.append(" and province like '%").append(bean.getProvince()).append("%'");
        }
        if (Strings.isNotBlank(bean.getCity())) {
            sb.append(" and city like '%").append(bean.getCity()).append("%'");
        }
        if (Strings.isNotBlank(bean.getDistrict())) {
            sb.append(" and district like '%").append(bean.getDistrict()).append("%'");
        }
        if (Strings.isNotBlank(bean.getCounty())) {
            sb.append(" and county like '%").append(bean.getCounty()).append("%'");
        }
        if (Strings.isNotBlank(bean.getCommunity())) {
            sb.append(" and community like '%").append(bean.getCommunity()).append("%'");
        }
        if (Strings.isNotBlank(bean.getCreateUserName())) {
            sb.append(" and create_user_name like '%").append(bean.getCreateUserName()).append("%'");
        }
        if (Strings.isNotBlank(bean.getType())) {
            sb.append(" and type like '%").append(bean.getType()).append("%'");
        }
        //数据库中存在这种"0001-01-01 00:00:00.000" 历史数据， 需要过滤掉
        sb.append(" and fill_date != '0001-01-01 00:00:00.000'");

        if (Strings.isNotBlank(bean.getQueryTime())) {
            String time[] = bean.getQueryTime().split(",");
            SimpleDateFormat SDF_START = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = new Date();
            date1.setTime(Long.parseLong(time[0]));
            Date date2 = new Date();
            date2.setTime(Long.parseLong(time[1]));
            sb.append(" and fill_date > '").append(SDF_START.format(date1)).append("' and fill_date < '").append(SDF_START.format(date2)).append("'");
        }
        sb.append(" order by fill_date desc");

        return sb.toString();
    }
}
